home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / program / ccdl150l.zip / SORT / BSEARCH.C next >
C/C++ Source or Header  |  1996-07-27  |  499b  |  22 lines

  1. #include <stdlib.h>
  2.  
  3. void *bsearch(const void *key, const void *base, size_t num, size_t width,
  4.             int (*compare)(const void *elem1, const void *elem2))
  5. {
  6.     size_t bottom = 0;
  7.     size_t top = num;
  8.     size_t mid;
  9.     int l;
  10.     while (1) {
  11.         mid = (top + bottom)/2;
  12.         if ((l=(*compare)(key,(char *)base + mid*width))== 0)
  13.             return (char *)base +mid * width;
  14.         if (l < 0)
  15.             top = mid;
  16.         else
  17.             bottom = mid;
  18.         if ((top +bottom)/2 == mid)
  19.             return 0;
  20.     }
  21.     return 0;    /* Never gets here */
  22. }